package com.wds.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wds.common.utils.JwtUtils;
import com.wds.common.utils.RedisCacheUtils;
import com.wds.common.utils.WebUtils;
import com.wds.domain.JsonResult;
import com.wds.domain.type.AppHttpCodeEnum;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-10-25 20:26
 * <p>
 * token校验过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCacheUtils redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (token == null || token.equals("") || request.getRequestURI().equals("/logout")) {
//            没有token，继续执行  （访问被拒或者可以匿名访问）
            filterChain.doFilter(request, response);
            return; //防止继续执行后面的逻辑
        }
        Claims claims = null;
        try {
            claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            // 向前端写回错误信息
            JsonResult result = JsonResult.http(AppHttpCodeEnum.NEED_LOGIN);
            ObjectMapper mapper = new ObjectMapper();
            WebUtils.renderString(response, mapper.writeValueAsString(result));
            log.error("token 无效： {}", request.getRequestURI());
            return;
//            throw new RuntimeException("token 无效");  过滤器的异常无法被全局异常处理器捕获
        }

        String key = "LoginAdmin:" + claims.getSubject();
        Object loginUser = redisCache.getCacheObject(key);

        if (loginUser == null) {
            JsonResult result = JsonResult.http(AppHttpCodeEnum.NEED_LOGIN);
            ObjectMapper mapper = new ObjectMapper();
            WebUtils.renderString(response, mapper.writeValueAsString(result));
            log.error("未知异常 redis无法取出对应LoginUser对象：{}", request.getRequestURI());
            return;
        }

        // TODO: 2022/10/26 封装权限
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request, response);
    }
}
